class Snake {
  // 蛇头
  head: HTMLElement;

  // 蛇的身体（包括蛇头）
  bodies: HTMLCollection;
  // 获取蛇的容器
  element: HTMLElement;
  constructor() {
    this.element = document.getElementById("snake")!;
    this.head = document.querySelector("#snake>div") as HTMLElement;
    this.bodies = this.element.getElementsByTagName("div");
  }
  //  获取蛇头坐标
  get X() {
    return this.head.offsetLeft;
  }
  get Y() {
    return this.head.offsetTop;
  }
  // 设置 蛇头坐标
  set X(value: number) {
    if (this.X === value) {
      return;
    }
    if (value < 0 || value > 290) {
      //    蛇死了  抛出异常
      throw new Error("蛇死了");
    }
    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft == value) {
      if (value > this.X) {
        value = this.X - 10;
      } else {
        value = this.X + 10;
      }
    }
    this.moveBody();
    this.head.style.left = value + "px";
    this.checkHeadBody()
    
  }
  set Y(value: number) {
    if (this.Y === value) {
      return;
    }
    //X 0-290
    if (value < 0 || value > 290) {
      //    蛇死了
      throw new Error("蛇死了");
    }

    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop == value) {
      if (value > this.Y) {
        value = this.Y - 10;
      } else {
        value = this.Y + 10;
      }
    }

    this.moveBody();

    this.head.style.top = value + "px";
    this.checkHeadBody()
  }
  //    蛇增加身体
  addBody() {
    this.element.insertAdjacentHTML("beforeend", "<div></div>");
  }
  //    蛇身体移动
  // 将后边身体设置为前边身体的位置
  // 一节一节 修改
  // 遍历获取所有的身体
  moveBody() {
    for (let i = this.bodies.length - 1; i > 0; i--) {
      // 获取前面的方块坐标
      let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
      let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;

      // 设置给后边
      (this.bodies[i] as HTMLElement).style.left = X + "px";
      (this.bodies[i] as HTMLElement).style.top = Y + "px";
    }
  }
  //   撞到自己
  checkHeadBody() {
    // 获取所有身体 检查 是否和蛇头坐标发生重叠
    for (let i = 1; i < this.bodies.length; i++) {
      let bd = this.bodies[i] as HTMLElement;
      if (this.X === bd.offsetLeft && this.Y === bd.offsetTop) {
        throw new Error("撞到自己啦");
      }
    }
  }
}

export default Snake;
